<?php
/**
 * Created by PhpStorm.
 * User: GIGABYTE
 * Date: 2016/6/22
 * Time: 19:05
 */

namespace MMC\Statistics\BaiDu;


use MMC\Statistics\BaiDu\Libs\DataApiConnect;
use MMC\Statistics\BaiDu\Libs\LoginConnection;
use MMC\Statistics\StatisticsInterface;

class BaiDu implements StatisticsInterface
{

    protected $config;

    protected $parameters = array(
        'reportid'      => 1,
        'siteid'        => null,
        'metrics'       => array('pageviews', 'visitors', 'ips', 'entrances', 'outwards', 'exits', 'stayTime', 'exitRate'),
        'dimensions'    => array('pageid'),
        'start_time'    => '',
        'end_time'      => '',
        'filters'       => array(),
        'start_index'   => 0,
        'max_results'   => 3000,
        'sort'          => array('pageviews desc'),
    );

    public function __construct(Config $config)
    {
        $this->config = $config;
    }

    /**
     * @param array $conditions
     * @return bool|int|string
     * @throws \Exception
     */
    public function getStatisticsData(array $conditions)
    {
        $loginService = new LoginService($this->config, new LoginConnection());

        $loginService->preLogin();

        if ($ret = $loginService->doLogin()) {
            if (!isset($ret['ucid']) || !isset($ret['st'])) {
                throw new \Exception("login error");
            }
        }

        $report = new ReportService($this->config, new DataApiConnect());

        $parameters = array_merge($this->parameters, $conditions);

        if (!$parameters['siteid']) {
            throw new \Exception("siteid is must");
        }

        $reportData = $report->query($ret['ucid'], $ret['st'], $parameters);

        if (false === $resultId = $report->getReportResultId($reportData)) {
            return false;
        }

        do {
            sleep(10);  //sleep, wait for generating result

            $statusInfo = $report->query($ret['ucid'], $ret['st'], array('result_id' => $resultId), ReportService::METHOD_GET_STATUS);

            if (false === $reportData = $report->getReportData($statusInfo)) {
                throw new \Exception("generating result fail");
            }

        } while(ReportService::STATUS_GENERATING === $reportData);

        //退出
        try {
            if (isset($ret['ucid']) && isset($ret['st'])) {
                $loginService->DoLogout($ret['ucid'], $ret['st']);
            }
        } catch (\Exception $e){}


        return $reportData;
    }


}